﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Framework.SqlSugar.Repository;

/// <summary>
/// SqlSugar 实体仓储
/// </summary>
/// <typeparam name="T"></typeparam>
public class SqlSugarRepository<T> : SimpleClient<T>, ISqlSugarRepository<T> where T : class, new()
{
	public SqlSugarRepository()
	{
		var iTenant = SqlSugarExtension.ITenant; // App.GetRequiredService<ISqlSugarClient>().AsTenant();
		Context = iTenant.GetConnectionScope(SqlSugarConst.MainConfigId);

		return;
	}

	#region 分表操作

	public async Task<bool> SplitTableInsertAsync(T input)
	{
		return await AsInsertable(input).SplitTable().ExecuteCommandAsync() > 0;
	}

	public async Task<bool> SplitTableInsertAsync(List<T> input)
	{
		return await AsInsertable(input).SplitTable().ExecuteCommandAsync() > 0;
	}

	public async Task<bool> SplitTableUpdateAsync(T input)
	{
		return await AsUpdateable(input).SplitTable().ExecuteCommandAsync() > 0;
	}

	public async Task<bool> SplitTableUpdateAsync(List<T> input)
	{
		return await AsUpdateable(input).SplitTable().ExecuteCommandAsync() > 0;
	}

	public async Task<bool> SplitTableDeleteableAsync(T input)
	{
		return await Context.Deleteable(input).SplitTable().ExecuteCommandAsync() > 0;
	}

	public async Task<bool> SplitTableDeleteableAsync(List<T> input)
	{
		return await Context.Deleteable(input).SplitTable().ExecuteCommandAsync() > 0;
	}

	public Task<T> SplitTableGetFirstAsync(Expression<Func<T, bool>> whereExpression)
	{
		return AsQueryable().SplitTable().FirstAsync(whereExpression);
	}

	public Task<bool> SplitTableIsAnyAsync(Expression<Func<T, bool>> whereExpression)
	{
		return Context.Queryable<T>().Where(whereExpression).SplitTable().AnyAsync();
	}

	public Task<List<T>> SplitTableGetListAsync()
	{
		return Context.Queryable<T>().SplitTable().ToListAsync();
	}

	public Task<List<T>> SplitTableGetListAsync(Expression<Func<T, bool>> whereExpression)
	{
		return Context.Queryable<T>().Where(whereExpression).SplitTable().ToListAsync();
	}

	public Task<List<T>> SplitTableGetListAsync(Expression<Func<T, bool>> whereExpression, string[] tableNames)
	{
		return Context.Queryable<T>().Where(whereExpression).SplitTable(t => t.InTableNames(tableNames)).ToListAsync();
	}

	#endregion 分表操作
}
